<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title></title>
        <link rel="stylesheet" type="text/css" href="../../../css/aui.css" />
        <script src="../../../script/jquery.js"></script>
        <script src="../../../CommonTool/commonNetWork.js"></script>
        <style>
            .ImageInfoBody {
                max-width: 8rem;
                min-width: 6rem;
                height: 8rem;
            }
            .marginBody {
                margin-top: 2%;
            }
            .NarrateBody {
                margin-top: 2%;
                max-width: 60vw;
                min-width: 12rem;
                height: 33vw;
            }
            .InfoContent {
                margin-top: 75%;
                margin-left: 6%;
            }
            #ThingOne {
                width: 100%;
                height: 10rem;
                margin-left: 1%;
                margin-top: 2%;
                background-size: 100%;
            }
            @media (min-width: 1240px) and (orientation: landscape) {
                .row-margin {
                    margin-top: 3%;
                }
            }

            /* === 新增：canvas 全屏样式 === */
            #crossCanvas.fullscreen {
                position: fixed;
                top: 0;
                left: 0;
                width: 100vw;
                height: 100vh;
                z-index: 9999;
                background-color: black;
            }
        </style>
    </head>
    <body>
        <header class="aui-bar aui-bar-nav" id="aui-header">
            <div class="aui-pull-left aui-btn" onclick="close_win();">
                <span class="aui-iconfont aui-icon-left"></span>返回
            </div>
            <div class="aui-title">基础-初级-视线追踪</div>
        </header>

        <div class="aui-row">
            <div class="aui-col-xs-4"></div>
            <div class="aui-col-xs-4">
                <div class="aui-btn aui-btn-primary StyleButton" id="SightstartButton">开始录制</div>
                <div class="aui-btn aui-btn-primary StyleButton" id="SightstopButton" style="display: none">
                    结束录制
                </div>
            </div>
        </div>

        <canvas id="crossCanvas" style="flex: 1; display: block; width: 100%"></canvas>
    </body>
    <script>
        var cameraRecorder;
        var screenRecorder;
        var isRecording = true;
        var token = "";
        var userid = "";
        var currentTimestamp = "";
        var operationName = "";
        var additionalInfo = "";
        var groupId = "";
        var scene = "基础";
        var sceneLevel = "初级";
        var courseType = "视线训练";
        var classSort = "6";
        var moodType = "";
        var remarks = "视线追踪";
        var classType = "学习";
        var startButton = document.getElementById("SightstartButton");
        var stopButton = document.getElementById("SightstopButton");
        let mediaRecorder;
        let chunks = [];
        let blob;
        let videoStream;
        var Nowdate = "";
        var NowdateString = "";
        let SightfileName = "";
        var intervalId = null;
        let csvstr = "";

        apiready = function () {
            token = api.pageParam.token;
            userid = api.pageParam.uid;
            groupId = api.pageParam.groupId;
            currentTimestamp = Date.now();
            operationName = "ing";
            additionalInfo = "";
            CommonNetWork();
            isRecording = true;
        };
        function InitialClick() {
            document.getElementById("InitialButton").style.display = "none";
            document.getElementById("InitialButton1").style.display = "block";
            document.getElementById("InitialButton4").style.display = "block";
        }
        function ShowInitialClick() {
            document.getElementById("InitialButton").style.display = "block";
            document.getElementById("InitialButton1").style.display = "none";
            document.getElementById("InitialButton4").style.display = "none";
        }
        function ResetClick() {
            history.go(0);
        }

        async function getCameraStream() {
            const constraints = {
                video: { facingMode: "user" },
            };
            return await navigator.mediaDevices.getUserMedia(constraints);
        }

        async function getMediaStream() {
            try {
                // 有权限的情况下获取媒体流
                videoStream = await navigator.mediaDevices.getUserMedia({
                    video: { facingMode: "user", width: 1920, height: 1080, frameRate: { ideal: 30 } },
                    audio: {
                        echoCancellation: true, // 启用回声消除
                    },
                });
                mediaRecorder = new MediaRecorder(videoStream);
                return videoStream;
            } catch (err) {
                api.alert("获取媒体流失败:", err);
            }
        }

        async function startRecording() {
           // === 新增：清空旧的数据 ===
            csvstr = "";
            var cameraStream;
            // 获取摄像头流和屏幕流
            try {
                cameraStream = await getMediaStream();
            } catch (err) {
                api.alert("获取媒体流失败:", err);
            }
            // 创建两个录制器
            cameraRecorder = new MediaRecorder(cameraStream);

            // 存储录制数据
            let cameraChunks = [];
            cameraRecorder.ondataavailable = (e) => cameraChunks.push(e.data);
            // 录制停止后的处理
            cameraRecorder.onstop = () => {
                const cameraBlob = new Blob(cameraChunks, { type: "video/webm" });
                uploadVideo(cameraBlob);
                saveCSV();
            };

            cameraRecorder.start();
            currentTimestamp = Date.now();

            // === 修改点：全屏显示 canvas ===
            const canvas = document.getElementById("crossCanvas");
            canvas.classList.add("fullscreen");
            const ctx = canvas.getContext("2d");
            canvas.width = window.innerWidth;
            canvas.height = window.innerHeight;

            let coords = [];
            let currentIndex = 0;

            coords = getRandomCoords(canvas.width, canvas.height);
            currentIndex = 0;

            console.log(canvas.width, canvas.height);
            console.log(JSON.stringify(coords));

            api.getSystemInfo({
                success: function (res) {
                    console.log(JSON.stringify(res));

                    intervalId = setInterval(() => {
                        if (currentIndex >= coords.length) {
                            stopRecording();
                            return;
                        }
                        const point = coords[currentIndex];
                        const timestamp = Date.now(); // 每次绘制时，获取当前时间戳
                        csvstr += `${timestamp},${currentIndex},${point.x * res.pixelRatio},${point.y*res.pixelRatio}\n`;

                        drawCross(ctx, canvas, point.x, point.y);
                        currentIndex++;
                    }, 3000);
                },
            });
        }

        function stopRecording() {
            if (cameraRecorder.state === "recording") {
                cameraRecorder.stop();
            }
            clearInterval(intervalId);

            // === 退出全屏样式 ===
            const canvas = document.getElementById("crossCanvas");
            canvas.classList.remove("fullscreen");
        }

        // 开始录制
        startButton.addEventListener("click", async () => {
            startRecording();
            startButton.style.display = "none";
            stopButton.style.display = "block";
        });

        // 停止录制
        stopButton.addEventListener("click", () => {
            stopRecording();
            startButton.style.display = "block";
            stopButton.style.display = "none";
        });

        // 生成随机坐标
        function getRandomCoords(width, height) {
            const arr = [];
            var xInterval = (width - 200) / 2;
            var yInterval = (height - 200) / 2;

            arr.push({ x: 100, y: 100 });
            arr.push({ x: 100 + xInterval, y: 100 });
            arr.push({ x: 100 + xInterval * 2, y: 100 });

            arr.push({ x: 100, y: 100 + yInterval });
            arr.push({ x: 100 + xInterval, y: 100 + yInterval });
            arr.push({ x: 100 + xInterval * 2, y: 100 + yInterval });

            arr.push({ x: 100, y: 100 + yInterval * 2 });
            arr.push({ x: 100 + xInterval, y: 100 + yInterval * 2 });
            arr.push({ x: 100 + xInterval * 2, y: 100 + yInterval * 2 });

            return arr;
        }

        // 绘制十字
        function drawCross(ctx, canvas, x, y, size = 20, color = "red") {
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            ctx.strokeStyle = color;
            ctx.lineWidth = 2;
            ctx.beginPath();
            ctx.moveTo(x - size, y);
            ctx.lineTo(x + size, y);
            ctx.moveTo(x, y - size);
            ctx.lineTo(x, y + size);
            ctx.stroke();
        }

        function uploadVideo(blob) {
            const blobChunk = blob;
            var chunkSize = 1024 * 1024;
            let start = 0;
            let count = 1;
            var totalPieces = Math.ceil(blobChunk.size / chunkSize);

            while (start < blobChunk.size) {
                var end = start + chunkSize;
                if (end > blobChunk.size) end = blobChunk.size;
                uploadChunk(blobChunk.slice(start, end), count, totalPieces, end == blobChunk.size);
                start += chunkSize;
                count++;
            }
        }

        function uploadChunk(chunk, count, totalPieces, bLast) {
            ImitatefileName =
                userid +
                "—" +
                scene +
                "—" +
                sceneLevel +
                "—" +
                courseType +
                "—" +
                classType +
                "—" +
                classSort +
                "—" +
                groupId +
                "—" +
                currentTimestamp +
                ".mp4";

            var formData = new FormData();
            formData.append("audioFile", chunk);
            formData.append("sliceNumber", count);
            formData.append("totalSlices", totalPieces);
            formData.append("fileName", ImitatefileName);
            formData.append("userid", userid);

            fetch(CommonUrl + "/test/uploadSlice", {
                method: "post",
                headers: {
                    Authorization: `Bearer ${token}`,
                },
                body: formData,
            })
                .then((res) => {
                    if (bLast) {
                        alert("上传成功");
                    }
                })
                .catch((res) => {
                    alert("上传失败");
                });
        }

        function saveCSV() {
            ImitatefileName =
                userid +
                "—" +
                scene +
                "—" +
                sceneLevel +
                "—" +
                courseType +
                "—" +
                classType +
                "—" +
                classSort +
                "—" +
                groupId +
                "—" +
                currentTimestamp +
                ".csv";

            api.writeFile(
                {
                    path: "fs://" + ImitatefileName,
                    data: csvstr,
                },
                function (ret, err) {
                    if (ret.status) {
                        alert("保存csv成功");
                    } else {
                        alert("保存csv失败");
                    }
                }
            );
        }
        function close_win() {
            currentTimestamp = Date.now();
            operationName = "end";
            additionalInfo = "out";
            CommonNetWork();
            api.openWin({
                name: "SubsetMenu-Basics",
                url: "../../SubsetMenu-Basics.html",
                pageParam: {
                    uid: userid,
                    token: token,
                },
                reload: true,
            });
        }
    </script>
</html>
